//
//  WHYOAuthViewController.swift
//  WHYWeibo-1.0
//
//  Created by 王洪运 on 15/11/23.
//  Copyright © 2015年 王洪运. All rights reserved.
//

import UIKit
import SVProgressHUD

class WHYOAuthViewController: UIViewController {
    
    private lazy var webView = UIWebView()
    
    @objc private func close () {
        
        view.endEditing(true)
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
        
    }
    
/// 自动填充账号密码
    @objc private func autoFill() {
        let js = "document.getElementById('userId').value = '15632137573';" +
        "document.getElementById('passwd').value = 'why71938183why.';"
        webView.stringByEvaluatingJavaScriptFromString(js)
    }
    
    override func loadView() {
        view = webView
        
        webView.delegate = self
        
        title = "登陆新浪微博"
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: .Plain, target: self, action: "autoFill")
    }

    override func viewDidLoad() {
            
        webView.loadRequest(NSURLRequest(URL: WHYNetWorkTools.sharedTools.oauthURL))
    }
    
}

extension WHYOAuthViewController: UIWebViewDelegate {
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        guard let url = request.URL where url.host == "www.baidu.com" else {
            return true
        }
        
        guard let qurey = url.query where qurey.hasPrefix("code=") else {
            close()
            return false
        }
        
        let code = qurey.substringFromIndex("code=".endIndex)
        
        WHYUserAccountViewModel.sharedUserAccount.loadAccessToken(code) { (isSuccessed) -> () in
            if !isSuccessed {
                SVProgressHUD.showErrorWithStatus("登陆失败了")
                delay(1.0) { self.close() }
            }
            
            SVProgressHUD.showSuccessWithStatus("登陆成功了")
            
            self.dismissViewControllerAnimated(false) {
                NSNotificationCenter.defaultCenter().postNotificationName(WHYWBSwitchViewControllerNotification, object: "welcome")
            }
            
        }
        
        return false
    }
    
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        
        if error?.code == 102 {
            SVProgressHUD.dismiss()
        }else {
            SVProgressHUD.showErrorWithStatus("您的网路不给力！")
        }
    }
    
}



